//
//  RJNetWork.m
//  AirQuality
//
//  Created by Po on 15/3/13.
//  Copyright (c) 2015年 Po. All rights reserved.
//

#import "RJNetWork.h"
#import "AFNetworking.h"
#import "AFHTTPRequestOperation.h"

@implementation RJNetWork

+ (void)myNetRequestWithAddress:(NSString *)address data:(NSDictionary *)data completeBlock:(void(^)(id responseObject))complete failBlack:(void(^)(id response))failBlock
{
    AFHTTPRequestOperationManager * manger = [AFHTTPRequestOperationManager manager];
    manger.requestSerializer.timeoutInterval = 60;
    AFSecurityPolicy *securityPolicy = [AFSecurityPolicy defaultPolicy];
    securityPolicy.allowInvalidCertificates = YES;
    manger.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", @"text/html", nil];
    [AFHTTPRequestOperationManager manager].securityPolicy = securityPolicy;
    [manger POST:address parameters:data success:^(AFHTTPRequestOperation *operation, id responseObject) {
        complete(responseObject);
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        //判断是否市州站登陆成功
        if (![RJUserData defaultRJUserData].isLogined && ![RJUserData defaultRJUserData].isProvince) {
            NSHTTPURLResponse * response = operation.response;
            NSURL * url = response.URL;
            NSString * urlString = [NSString stringWithFormat:@"%@",url];
            //http://221.237.179.54
            NSString * checkSuccessURL = [NSString stringWithFormat:@"http://www.scnewair.cn:%@/smartadmin/index.htm",[RJUserData defaultRJUserData].currentCityCode];
            if ([urlString isEqualToString:checkSuccessURL]) {
                complete(@{@"reason":@"登陆成功",@"result":@"1"});
                return;
            }
        }
//        [self ShowNoNetMsg];
        failBlock(error);
    }];
}

+ (void)myNetRequestWithAddress1:(NSString *)address data:(NSDictionary *)data completeBlock:(void(^)(id responseObject))complete failBlack:(void(^)(id response))failBlock
{
    AFHTTPRequestOperationManager * manger = [AFHTTPRequestOperationManager manager];
    AFSecurityPolicy *securityPolicy = [AFSecurityPolicy defaultPolicy];
    securityPolicy.allowInvalidCertificates = YES;
//    manger.requestSerializer = [AFHTTPRequestSerializer serializer];
//    manger.responseSerializer = [AFHTTPResponseSerializer serializer];
    manger.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", @"text/html", nil];
    [AFHTTPRequestOperationManager manager].securityPolicy = securityPolicy;
    //    if ([address rangeOfString:@"/smartadmin/statAnalyse/getHourData"].location != NSNotFound) {
    //        manger.requestSerializer = [AFHTTPRequestSerializer serializer];
    //        manger.responseSerializer = [AFHTTPResponseSerializer serializer];
    //        manger.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];
    //    }
    [manger POST:address parameters:data success:^(AFHTTPRequestOperation *operation, id responseObject) {
//        NSData *doubi = responseObject;
//        NSString *shabi =  [[NSString alloc]initWithData:doubi encoding:NSUTF8StringEncoding];
//        NSLog(@"----%@",shabi);
        complete(responseObject);
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        //判断是否市州站登陆成功
        if (![RJUserData defaultRJUserData].isLogined && ![RJUserData defaultRJUserData].isProvince) {
            NSHTTPURLResponse * response = operation.response;
            NSURL * url = response.URL;
            NSString * urlString = [NSString stringWithFormat:@"%@",url];
            NSString * checkSuccessURL = [NSString stringWithFormat:@"http://www.scnewair.cn:%@/smartadmin/index.htm",[RJUserData defaultRJUserData].currentCityCode];
            if ([urlString isEqualToString:checkSuccessURL]) {
                complete(@{@"reason":@"登陆成功",@"result":@"1"});
                return;
            }
        }
        //        [self ShowNoNetMsg];
        failBlock(error);
    }];
}

+ (void)myNetGetWithAddress:(NSString *)address data:(NSDictionary *)data completeBlock:(void(^)(id responseObject))complete
{
    AFHTTPRequestOperationManager * manger = [AFHTTPRequestOperationManager manager];
//    [manger GET:@"http://newair.scemc.cn:5100/smartadmin/statAnalyse/getHourData?type=3&area=5101&starttime=2015-05-20%2001:00:00&endtime=2015-05-20%2023:00:00&gaslist=SO2,NO2,O3,PM10,PM2.5,CO&comstarttime=2015-05-21%2000:00:00&comendtime=2015-05-21%2020:00:00" parameters:nil success:^(NSURLSessionDataTask *task, id responseObject) {
//        complete(responseObject);
//    } failure:^(NSURLSessionDataTask *task, NSError *error) {
//        [self ShowNoNetMsg];
//    }];
    [manger GET:address parameters:data success:^(AFHTTPRequestOperation *operation, id responseObject) {
        complete(responseObject);
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [self ShowNoNetMsg];
    }];
}

+ (void)ShowNoNetMsg
{
    UIAlertController * alert = [UIAlertController alertControllerWithTitle:@"网络异常" message:@"网络连接失败，请检查网络连接或稍后再试！" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction * okAction= [UIAlertAction actionWithTitle:@"好的" style:UIAlertActionStyleCancel handler:nil];
    [alert addAction:okAction];
    [sysWindow.rootViewController presentViewController:alert animated:YES completion:nil];
}

+ (AFSecurityPolicy*)customSecurityPolicy
{
    // /先导入证书
    NSString *cerPath = [[NSBundle mainBundle] pathForResource:@"client" ofType:@"cer"];//证书的路径
    NSData *certData = [NSData dataWithContentsOfFile:cerPath];
    
    // AFSSLPinningModeCertificate 使用证书验证模式
    AFSecurityPolicy *securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeCertificate];
  
    // allowInvalidCertificates 是否允许无效证书（也就是自建的证书），默认为NO
    // 如果是需要验证自建证书，需要设置为YES
    securityPolicy.allowInvalidCertificates = YES;
    
    //validatesDomainName 是否需要验证域名，默认为YES；
    //假如证书的域名与你请求的域名不一致，需把该项设置为NO；如设成NO的话，即服务器使用其他可信任机构颁发的证书，也可以建立连接，这个非常危险，建议打开。
    //置为NO，主要用于这种情况：客户端请求的是子域名，而证书上的是另外一个域名。因为SSL证书上的域名是独立的，假如证书上注册的域名是www.google.com，那么mail.google.com是无法验证通过的；当然，有钱可以注册通配符的域名*.google.com，但这个还是比较贵的。
    //如置为NO，建议自己添加对应域名的校验逻辑。
    securityPolicy.validatesDomainName = YES;
    securityPolicy.validatesCertificateChain = NO;
    securityPolicy.pinnedCertificates = @[certData];
    
    return securityPolicy;
}

+ (void)sendNetworkRequestWithUrl1:(NSString *)url Dic:(NSDictionary *)parameters Complete:(void(^)(BOOL succeed, id responseObject))complete{
    
    // 1.获得请求管理者
    AFHTTPRequestOperationManager *mgr = [AFHTTPRequestOperationManager manager];
    // 2.申明返回的结果是text/html类型
    mgr.responseSerializer = [AFHTTPResponseSerializer serializer];
    // 加上这行代码，https ssl 验证。
    [mgr setSecurityPolicy:[self customSecurityPolicy]];
    [mgr POST:@"https://192.168.1.193:8443/mpos/pay/unifiedorder" parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSLog(@"%@",responseObject);
        complete(YES, responseObject);
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"1111");
    }];
    // 3.发送POST请求
//    [mgr POST:url parameters:parameters
//      success:^(AFHTTPRequestOperation *operation, id responseObj) {
//          if (success) {
//              success(responseObj);
//          }
//      } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
//          if (failure) {
//              failure(error);
//          }
//      }];
    
}
+ (void)sendNetworkRequestWithUrl:(NSString *)url Dic:(NSDictionary *)parameters Complete:(void(^)(BOOL succeed, id responseObject))complete {
    /**
     *  拼接地址
     */
    NSString *completeUrl = [NSString stringWithFormat:@"%@", url];
//    AFSecurityPolicy *securityPolicy = [AFSecurityPolicy defaultPolicy];
//    securityPolicy.allowInvalidCertificates = YES;
//    [AFHTTPRequestOperationManager manager].securityPolicy = securityPolicy;
    /**
     *  初始化网络请求
     */
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.securityPolicy.allowInvalidCertificates = YES;
    /**
     *  设置网络请求超时时间
     */
    manager.requestSerializer.timeoutInterval = 60;
    /**
     *  设置MIME类型
     */
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", @"text/html", nil];
    /**
     *  发起网络请求
     */
    [manager POST:completeUrl parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
//        NSLog(@"1111%@",responseObject);
        complete(YES, responseObject);
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        complete(NO, nil);
      
    }];
}

@end
